#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "chan.h"

chan_t* done;

void* worker(void *jobs) {
	// Process jobs until channel is closed.
	void* job;
	while (chan_recv((chan_t *) jobs, &job) == 0) {
		printf("received job %s\n", (char *) job);
		fflush(stdout);
		free((char *)job);
	}

	// Notify that all jobs were received.
	printf("received all jobs\n");
	fflush(stdout);
	chan_send(done, "1");
	return NULL;
}

int main() {
	chan_t* jobs;

	// Initialize channels.
	jobs = chan_init(5);
	done = chan_init(0);

	pthread_t th;
	pthread_create(&th, NULL, worker, (void *) jobs);

	// Send 10 jobs over the jobs channel then close it.
	int i;
	char *ptr = NULL;
	for (i = 1; i <= 10; i++) {
		ptr = (char *)calloc (32,sizeof(char));
		snprintf(ptr, 32, "sent%d", i);
		chan_send(jobs, (void*)ptr);
		printf("sent job %s\n", ptr);
		fflush(stdout);
	}
	chan_close(jobs);
	printf("sent all jobs\n");
	fflush(stdout);

	// Wait for all jobs to be received.
	chan_recv(done, NULL);

	// Clean up channels.
	chan_dispose(jobs);
	chan_dispose(done);
}
